package org.piaohao.howtodoit.usermanager;

import cn.hutool.db.dialect.DialectName;
import com.jfinal.config.*;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.Sqlite3Dialect;
import com.jfinal.template.Engine;
import com.jfinal.template.source.ClassPathSourceFactory;
import com.zaxxer.hikari.HikariDataSource;
import org.piaohao.fast.jfinal.Bootstrap;
import org.piaohao.fast.jfinal.LogRequestInterceptor;

import javax.sql.DataSource;

public class MainApp extends JFinalConfig {

    @Override
    public void configConstant(Constants constants) {
        PropKit.use("app.properties");
        constants.setDevMode(PropKit.getBoolean("devMode", false));
        PathKit.setWebRootPath("templates");
    }

    @Override
    public void configRoute(Routes routes) {
        routes.add("/", UserController.class, "");
    }

    @Override
    public void configEngine(Engine engine) {
        engine.setSourceFactory(new ClassPathSourceFactory());
    }

    @Override
    public void configPlugin(Plugins plugins) {
        ActiveRecordPlugin arp = new ActiveRecordPlugin(
                createDatasource(PropKit.get("jdbc.url"), PropKit.get("jdbc.username"), PropKit.get("jdbc.password")));
        arp.setDialect(new Sqlite3Dialect());
        arp.addMapping("user", "email", User.class);
        plugins.add(arp);
    }

    @Override
    public void configInterceptor(Interceptors interceptors) {
        interceptors.add(new LogRequestInterceptor());
        interceptors.add(new LoginInterceptor());
    }

    @Override
    public void configHandler(Handlers handlers) {

    }

    private DataSource createDatasource(String url, String username, String password) {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setDriverClassName("org.sqlite.JDBC");
        hikariDataSource.setJdbcUrl(url);
        hikariDataSource.setUsername(username);
        hikariDataSource.setPassword(password);
        hikariDataSource.setMaxLifetime(1765000);
        hikariDataSource.setMaximumPoolSize(15);
        return hikariDataSource;
    }

    public static class Const {
        static final String SESSION_KEY = "userId";
    }

    public static void main(String[] args) {
        Bootstrap.run(args);
    }
}
